/*
 * Created by sunlw
 * 2018-11-23
 * 地图查询功能。
 */

//查询面图层
function showProvincePolygons() {
  var sql = "";
    for (var i = 0; i < ghighlightProvince.length; i++) {
      sql += "AREA_ID='" + ghighlightProvince[i] + "' or ";
    }
    var ilen = sql.length;
    var sql = sql.substr(0, ilen - 3);
    QueryBySQL(config.urlAddr + config.urlNational, sql, showProvincePolygonsCallback, queryError, null);
}

var color_arr = ["#9370DB","#FFC1C1", "#7D7DFF", "#FF6699", "#9370DB",
  "#FFEC8B", "#FFB6C1", "#4B32B4", "#2894FF", "#FF8EFF", "#FFC0CB",
  "#FFA500", "#D2691E", "#F5DEB3", "#B0C4DE", "#FFB6C1", "#FF6699",
  "#EEE8AA", "#FFC1C1", "#FF8247", "#EE82EE", "#9370DB", "#FF7F00"];

//查询面图层返回结果
function showProvincePolygonsCallback(res) {
    graphicLayerPolygon.clear();
    graphicLayerPolygonLabel.clear();
    for (var i = 0; i < res.features.length; i++) {
        // if (graphicLayerPolygonsArray.indexOf(res.features[i].attributes.Id) > -1) {//判断该要素是否被添加，如果添加跳出
        //   continue;
        // }
        // graphicLayerPolygonsArray.push(res.features[i].attributes.Id);
        var attribute = res.features[i].attributes;
        attribute.layerID = "provincePolygon";
        var geo = res.features[i].geometry;
        var graphic;

        // objData.data.screenSelect
        var city = "";
        if (attribute.NAME == "辽宁省")
          city = "大连市";
        else if (attribute.NAME == "江苏省")
          city = "无锡市";
        else if (attribute.NAME == "北京市")
          city = "北京市";
        var count = getCommunityPointCount(city);
        if (count > 0 && count <= 500) {
          graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF0000"), attribute);
        }
        else if (count > 500 && count <= 1000) {
          graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF00FF"), attribute);
        }
        else if (count == 0) {
          graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FFFFFF"), attribute);
        }
        graphicLayerPolygon.add(graphic);
        // addPopo(graphicLayerPolygonLabel, geo.getExtent().getCenter().x, geo.getExtent().getCenter().y,
        //     "", 25, 25, attribute, attribute.NAME, "11pt", -30, -4, configColor.Black);
    }
}

// 显示市级面
function showCityPolygons() {
  var sql = "";
  for (var i = 0; i < ghighlightCity.length; i++) {
    sql += "AREA_ID='" + ghighlightCity[i] + "' or ";
  }
  var ilen = sql.length;
  var sql = sql.substr(0, ilen - 3);
  QueryBySQL(config.urlAddr + config.urlProvince, sql, showCityPolygonsCallback, queryError, null);
}

function showCityPolygonsCallback(res) {
    graphicLayerPolygon.clear();
    graphicLayerPolygonLabel.clear();
    for (var i = 0; i < res.features.length; i++) {
        // if (graphicLayerPolygonsArray.indexOf(res.features[i].attributes.Id) > -1) {//判断该要素是否被添加，如果添加跳出
        //     continue;
        // }
        // graphicLayerPolygonsArray.push(res.features[i].attributes.Id);

        var attribute = res.features[i].attributes;
        attribute.layerID = "cityPolygon";
        var geo = res.features[i].geometry;
        // var graphic = new esri.Graphic(geo, getPolygonStyleByColor(color_arr[i]), attribute);
        // graphicLayerPolygon.add(graphic);
      var graphic;

      var count = 0;

      var count = getCommunityPointCount(attribute.NAME);
      if (count > 0 && count <= 500) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF0000"), attribute);
      }
      else if (count > 500 && count <= 1000) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF00FF"), attribute);
      }
      else if (count == 0) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FFFFFF"), attribute);
      }
      graphicLayerPolygon.add(graphic);
        // addPopo(graphicLayerPolygonLabel, geo.getExtent().getCenter().x, geo.getExtent().getCenter().y,
        //   "", 25, 25, attribute, attribute.NAME, "11pt", -10, 0, configColor.Black);
    }
}

function showCityPolygonsGray() {
  var sql = "";
  for (var i = 0; i < ghighlightProvince.length; i++) {
    sql += "PARENT_AREA='" + ghighlightProvince[i] + "' or ";
  }
  var ilen = sql.length;
  var sql = sql.substr(0, ilen - 3);
  QueryBySQL(config.urlAddr + config.urlProvince, sql, showCityPolygonsGrayCallback, queryError, null);
}

function showCityPolygonsGrayCallback(res) {
  graphicLayerPolygonGray.clear();
  graphicLayerPolygonLabel.clear();
  for (var i = 0; i < res.features.length; i++) {
    var attribute = res.features[i].attributes;
    attribute.layerID = "cityPolygonGray";
    var geo = res.features[i].geometry;
    var graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FFFFFF"), attribute);
    graphicLayerPolygonGray.add(graphic);
  }
}

// 查询显示地级面图层
function showDistrictPolygons() {
  var sql = "";
  for (var i = 0; i < ghighlightDistrict.length; i++) {
    sql += "AREA_ID='" + ghighlightDistrict[i] + "' or ";
  }
  var ilen = sql.length;
  var sql = sql.substr(0, ilen - 3);
  console.log("区：",sql);
  QueryBySQL(config.urlAddr + config.urlDistrict, sql, showDistrictPolygonsCallback, queryError, null);
}

function showDistrictPolygonsCallback(res) {
    graphicLayerPolygon.clear();
    graphicLayerPoint.clear();
    graphicLayerPolygonLabel.clear();
    for (var i = 0, len = res.features.length; i < len; i++) {
        // if (graphicLayerPolygonsArray.indexOf(res.features[i].attributes.Id) > -1) {//判断该要素是否被添加，如果添加跳出
        //     continue;
        // }
        // graphicLayerPolygonsArray.push(res.features[i].attributes.Id);
        var graphic;
        var attribute = res.features[i].attributes;
        attribute.layerID = "districtPolygon";
        var geo = res.features[i].geometry;

        var city = "";
      if (attribute.NAME == "西岗区" || attribute.NAME == "中山区" || attribute.NAME == "甘井子区" || attribute.NAME == "沙河口区"
        || attribute.NAME == "旅顺口区"
        || attribute.NAME == "金州区" || attribute.NAME == "普兰店区" || attribute.NAME == "瓦房店市" || attribute.NAME == "庄河市" )
        city = "大连市";
      else if  (attribute.NAME == "昌平区" || attribute.NAME == "海淀区")
        city = "北京市";
      var count = getCommunityPointCount(city);
      if (count > 0 && count <= 500) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF0000"), attribute);
      }
      else if (count > 500 && count <= 1000) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FF00FF"), attribute);
      }
      else if (count == 0) {
        graphic = new esri.Graphic(geo, getPolygonStyleByColor("#FFFFFF"), attribute);
      }
      graphicLayerPolygon.add(graphic);

        // var graphic = new esri.Graphic(geo, getPolygonStyleByColor(color_arr[i]), attribute);
        // graphicLayerPolygon.add(graphic);
        // addPopo(graphicLayerPolygonLabel, geo.getExtent().getCenter().x, geo.getExtent().getCenter().y,
        //   "", 25, 25, attribute, attribute.NAME, "11pt", -10, 0, configColor.Black);
    }
}

// 显示小区级别
function showCommunity(url) {
  var sql = "1=1";
  //objQuery.sqlQuery(url, sql, showCommunityCallback, ExtentToPolygon(map));
  QueryBySQL(url, sql, showCommunityCallback, errback, ExtentToPolygon(map));
}

function showCommunityCallback(res) {
    //graphicLayerPolygon.clear();
    graphicLayerPoint.clear();
    for (var i = 0, len = res.features.length; i < len; i++) {
        // if (graphicLayerPolygonsArray.indexOf(res.features[i].attributes.Id) > -1) {//判断该要素是否被添加，如果添加跳出
        //     continue;
        // }
        // graphicLayerPolygonsArray.push(res.features[i].attributes.Id);

        var geo = res.features[i].geometry;
        var src = 'img/map.png';
        var attribute = res.features[i].attributes;
        attribute.layerID = "XQ";

        var attr = [];
        attr.x = parseFloat(geo.x);
        attr.y = parseFloat(geo.y);
        //_extent.push(attr);
        addPopo(graphicLayerPoint, geo.x, geo.y, src, 15, 15, attribute, attribute.LABEL, "9pt", 5, 13, configColor.Black);
    }
    // 定位
    if (_extent.length) {
        var temp = objGeometry.createExtentByPoints(_extent);
        map.setExtent(temp);
    }
}

function returnExtent(pts) {
    require([
        "esri/geometry/Extent",
        "esri/geometry/SpatialReference"
    ],function(
        Extent,
        SpatialReference) {
        var minx = 0;
        var maxx = 0;
        var miny = 0;
        var maxy = 0;
        for (var i = 0; i < pts.length; i++) {
            if (minx == 0 || maxx == 0 || miny == 0 || maxy == 0) {
                minx = pts[i].x;
                maxx = pts[i].x;
                miny = pts[i].y;
                maxy = pts[i].y;
                continue;
            }
            if (minx > pts[i].x) {
                minx = pts[i].x;
            }
            if (maxx < pts[i].x) {
                maxx = pts[i].x;
            }
            if (miny > pts[i].y) {
                miny = pts[i].y;
            }
            if (maxy < pts[i].y) {
                maxy = pts[i].y;
            }
        }
        var extents = {
            type: "extent",
            xmin: minx,
            ymin: miny,
            xmax: maxx,
            ymax: maxy,
            spatialReference: 3785
        };
        view.extent = extents;
    });
}

//小区查询
function queryXQ(cityCode) {
   var url;
   if (cityCode == "大连市")
     url = config.cityData_DL + config.urlCommunity;
   else if (cityCode == "北京市")
     url = config.cityData_BJ + config.urlCommunity;
   else if (cityCode == "丹东市")
     url = config.cityData_DD + config.urlCommunity;
   else if (cityCode == "珠海市")
     url = config.cityData_ZH + config.urlCommunity;
   else if (cityCode == "成都市")
     url = config.cityData_CD + config.urlCommunity;
   else if (cityCode == "南京市")
     url = config.cityData_NJ + config.urlCommunity;
    objQuery.sqlQuery(url, "1=1", queryXQcallback, errback, ExtentToPolygon(map));
}

//小区查询返回结果
function queryXQcallback(res) {
    graphicLayer.clear();
    for (var i = 0; i < res.features.length; i++) {
        // if(graphicLayerDataArray.indexOf(res[i].feature.attributes.ADDRESS_ID) > -1){//该要素已经添加到graphicLayer
        //     continue;
        // }
        // graphicLayerDataArray.push(res[i].feature.attributes.ADDRESS_ID);

        var geo = res.features[i].geometry;
        var src = 'img/map.png';
        var attribute = res.features[i].attributes;
        attribute.layerID = "XQ";

        addPopo(graphicLayer, geo.x, geo.y, src, 15, 15, attribute, attribute.LABEL, "9pt", 5, 13, configColor.Black);
    }
}

function errback(res) {

}

// 查询小区，并定位到指定的位置
function queryXQAndZoomToMap(cityName, AddressID) {
  var sql = "ADDRESS_ID=" + AddressID;
  if (cityName == "北京市")
    QueryBySQL(config.cityData_BJ + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
  else if (cityName == "大连市")
    QueryBySQL(config.cityData_DL + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
  else if (cityName == "丹东市")
    QueryBySQL(config.cityData_DD + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
  else if (cityName == "珠海市")
    QueryBySQL(config.cityData_ZH + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
  else if (cityName == "成都市")
    QueryBySQL(config.cityData_CD + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
  else if (cityName == "南京市")
    QueryBySQL(config.cityData_NJ + config.urlCommunity, sql, queryXQAndZoomToMapcallBack, errback, ExtentToPolygon(map));
}

function queryXQAndZoomToMapcallBack(res) {
  graphicLayer.clear();
  for (var i = 0; i < res.features.length; i++) {
    var geo = res.features[i].geometry;
    var src = 'img/point_4.png';
    var attribute = res.features[i].attributes;
    attribute.layerID = "XQ";
    addPopo(graphicLayerOldPoint, geo.x, geo.y, src, 25, 25, attribute, attribute.LABEL, "9pt", 5, 13, configColor.Black);
    map.centerAndZoom(geo, config.showMapGJXQ);
    var obj = {};
    obj.id = attribute.ADDRESS_ID;
    obj.name = attribute.LABEL;
    obj.x = geo.x;
    obj.y = geo.y;
    setXQInfo(obj);
  }
}

// 查询楼栋
function queryBuildingByAddressID(cityCode, AddressID) {
  var url;
  var sql = "ADDRESS_ID=" + AddressID;
  if (cityCode == "大连市")
    url = config.cityData_DL + config.urlBuilding;
  else if (cityCode == "北京市")
    url = config.cityData_BJ + config.urlBuilding;
  else if (cityCode == "丹东市")
    url = config.cityData_DD + config.urlBuilding;
  else if (cityCode == "珠海市")
    url = config.cityData_ZH + config.urlBuilding;
  else if (cityCode == "成都市")
    url = config.cityData_CD + config.urlBuilding;
  else if (cityCode == "南京市")
    url = config.cityData_NJ + config.urlBuilding;

  QueryBySQL(url, sql, queryBuildingByAddressIDcallBack, queryError, null);
}

function queryBuildingByAddressIDcallBack(res) {
  for (var i = 0; i < res.features.length; i++) {
    // if(graphicLayerDataArray.indexOf(res[i].feature.attributes.ADDRESS_ID) > -1){//该要素已经添加到graphicLayer
    //     continue;
    // }
    // graphicLayerDataArray.push(res[i].feature.attributes.ADDRESS_ID);

    var geo = res.features[i].geometry;
    var src = 'img/map.png';
    var attribute = res.features[i].attributes;
    attribute.layerID = "Building";
    attribute.buildingCode = LdCode;
    map.centerAndZoom(geo, config.zoomBuilding);
    addPopo(graphicLayerPoint, geo.x, geo.y, src, 15, 15, attribute, attribute.LABEL, "9pt", 5, 13, configColor.Blue);
  }
}

// 查询省
function queryProvince(AREA_ID) {
  var sql = "AREA_ID='" + AREA_ID + "'";
  QueryBySQL(config.urlAddr + "/0", sql, queryProvincecallBack, queryError, null);
}

function queryProvincecallBack(res) {
  for (var i = 0; i < res.features.length; i++) {
    provinceName = res.features[0].attributes.NAME;

    // msg.province = provinceName;
    // msg.city = cityName;
    // msg.district = districtName;
    // sendMessage(msg);
  }
}

// 查询市
function queryCity(AREA_ID) {
  var sql = "AREA_ID = '" + AREA_ID + "'";
  QueryBySQL(config.urlAddr + "/1", sql, queryCitycallBack, queryError, null);
}

function queryCitycallBack(res) {
  for (var i = 0; i < res.features.length; i++) {
    cityName = res.features[0].attributes.NAME;
    parentArea_ID = res.features[0].attributes.PARENT_AREA;
    queryProvince(parentArea_ID);
  }
}

// 查询小区，根据小区名，返回坐标
function queryCommunityByName(Name) {
  var sql = "LABEL='" + Name + "'";
  QueryBySQL(config.cityData_DL + config.urlCommunity, sql, queryCommunityByNamecallBack, errback, null);
}

function queryCommunityByNamecallBack(res) {
  for (var i = 0; i < res.features.length; i++) {
    coordx = res.features[0].geometry.x;
    coordy = res.features[0].geometry.y;
    communityID = res.features[0].attributes.ADDRESS_ID;
  }
}

function queryCityXY(AREA_ID) {
  var sql = "PARENT_AREA = '" + AREA_ID + "'";
  QueryBySQL(config.urlAddr + "/1", sql, queryCityXYcallBack, queryError, null);
}

function queryCityXYcallBack(res) {
  //for (var i = 0; i < res.features.length; i++) {
    // cityName = res.features[0].attributes.NAME;
    // parentArea_ID = res.features[0].attributes.PARENT_AREA;
    // queryProvince(parentArea_ID);
    var pt = createPoint(parseFloat(res.features[0].geometry.getExtent().getCenter().x),
      parseFloat(res.features[0].geometry.getExtent().getCenter().y));
    map.centerAndZoom(pt, config.zoomCity);
  //}
}

function queryDistrictXY(AREA_ID) {
  var sql = "PARENT_AREA = '" + AREA_ID + "'";
  QueryBySQL(config.urlAddr + "/2", sql, queryDistrictXYcallBack, queryError, null);
}

function queryDistrictXYcallBack(res) {
  var pt = createPoint(parseFloat(res.features[0].geometry.getExtent().getCenter().x),
    parseFloat(res.features[0].geometry.getExtent().getCenter().y));
  map.centerAndZoom(pt, config.zoomDistrict);
}

/********************************************************/
//查询楼栋面
function queryLDR() {
  console.log("查询楼栋面...");
  var geo = ExtentToPolygon(map);
  var query = new esri.tasks.Query();
  var queryTask = new esri.tasks.QueryTask(config.urlIndoor+config.urlIndoor_build);
  query.where = " 1=1 ";
  query.outSpatialReference = map.spatialReference;
  query.geometry = geo;
  query.returnGeometry = true;
  query.outFields = ["*"];
  queryTask.execute(query, (function(res){
    console.log("楼栋面：",res.features);
    for (var i = 0; i < res.features.length; i++) {
      if(graphicLayerDataArray.indexOf(res.features[i].attributes.BUILD_ID) > -1){//该要素已经添加到graphicLayer
        continue;
      }
      graphicLayerDataArray.push(res.features[i].attributes.BUILD_ID);

      var graphic = res.features[i];
      var symbol = getPolygonStyle();
      graphic.attributes.layerID = "LDR";

      var graf = new esri.Graphic(graphic.geometry, symbol, graphic.attributes);
      graphicLayerPolygonGray.add(graf);
      var geo = graphic.geometry.getExtent().getCenter();
      //添加楼栋标签
      var label = res.features[i].attributes.BUILD_NAME;
      if(label){
        var src = "img/point_2.png";
        addPopo(buildPointLayer, geo.x, geo.y, src, 20, 20, graphic.attributes, label, "9pt", 10, 5, 0);
      }
    }
  }), (function(){console.log("查询失败...")}));
}

function queryLandR(){
  var geo = ExtentToPolygon(map);
  var query = new esri.tasks.Query();
  var queryTask = new esri.tasks.QueryTask(config.urlIndoor+config.urlIndoor_land);
  query.where = " 1=1 ";
  query.outSpatialReference = map.spatialReference;
  query.geometry = geo;
  query.returnGeometry = true;
  query.outFields = ["*"];
  queryTask.execute(query, (function(res){
    console.log("土地面：",res.features);
    for (var i = 0; i < res.features.length; i++) {
      if(graphicLayerDataArray.indexOf(res.features[i].attributes.LOCATION_ID) > -1){//该要素已经添加到graphicLayer
        continue;
      }
      graphicLayerDataArray.push(res.features[i].attributes.LOCATION_ID);

      var graphic = res.features[i];
      var symbol = getPolygonStyle();
      graphic.attributes.layerID = "LANDR";

      var graf = new esri.Graphic(graphic.geometry, symbol, graphic.attributes);
      landLayer.add(graf);
    }
  }), (function(){console.log("查询土地失败...")}));
}

